package com.qubuyer.business.mine.activity

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.qubuyer.R
import com.qubuyer.bean.event.GoToMainEvent
import com.qubuyer.business.auth.view.ForgetPwdFragment
import com.qubuyer.business.auth.view.UpdatePhoneStepFirstFragment
import com.qubuyer.business.mine.viewmodel.SettingViewModel
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.customview.BottomUpDialog
import com.qubuyer.databinding.FragmentSettingBinding
import com.qubuyer.utils.DialogUtil
import com.qubuyer.utils.EventBusUtil
import com.qubuyer.utils.FileUtil
import com.qubuyer.utils.NavigationUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.devio.takephoto.app.TakePhoto
import org.devio.takephoto.app.TakePhotoImpl
import org.devio.takephoto.model.InvokeParam
import org.devio.takephoto.model.TContextWrap
import org.devio.takephoto.model.TResult
import org.devio.takephoto.permission.PermissionManager
import org.devio.takephoto.permission.PermissionManager.TPermissionType
import org.devio.takephoto.permission.TakePhotoInvocationHandler
import java.io.File

class SettingFragment : MVVMFragment<FragmentSettingBinding, SettingViewModel>() {

    private var mInvokeParam: InvokeParam? = null

    private val takePhoto: TakePhoto by lazy {
        TakePhotoInvocationHandler.of { invokeParam ->
            val type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.method)
            if (TPermissionType.WAIT == type) {
                this.mInvokeParam = invokeParam
            }
            type
        }.bind(TakePhotoImpl(this, object : TakePhoto.TakeResultListener {
            override fun takeSuccess(result: TResult?) {
                result?.images?.firstOrNull()?.originalPath?.let { path ->
                    if (FileUtils.getFileLength(path) / 1048576 > 2) {
                        launch {
                            showProgressDialog()
                            withContext(Dispatchers.IO) {
                                var bitmap: Bitmap? = ImageUtils.getBitmap(path)
                                bitmap = ImageUtils.bytes2Bitmap(ImageUtils.compressByQuality(bitmap, java.lang.Long.valueOf((500 * 1024).toLong())))
                                ImageUtils.save(bitmap, path, Bitmap.CompressFormat.JPEG)
                            }
                            viewModel.updateHeadImg(File(path))
                        }
                    } else {
                        viewModel.updateHeadImg(File(path))
                    }
                }
            }

            override fun takeFail(result: TResult?, msg: String?) {
                toast(msg.toString())
            }

            override fun takeCancel() {
            }
        })) as TakePhoto
    }

    private val mBottomUpDialog: BottomUpDialog by lazy {
        BottomUpDialog(mContext, arrayOf("拍照", "从相册选择")) { position ->
            when (position) {
                0 -> takePhoto.onPickFromCapture(getFilePath())
                1 -> takePhoto.onPickFromGallery()
            }
            mBottomUpDialog.dismiss()
        }
    }

    override fun onDataBinding(dataBinding: FragmentSettingBinding) {
        dataBinding.host = this
    }

    override fun getTitle(): String {
        return "设置"
    }

    override val viewModel: SettingViewModel by injectVMByActivity()
    override val layoutId: Int
        get() = R.layout.fragment_setting

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewDataBinding.tvVersion.text = "v${AppUtils.getAppVersionName()}"
        viewModel.userEntity.observe(viewLifecycleOwner, {
            Glide.with(this@SettingFragment).load(it.head_pic).circleCrop().placeholder(R.drawable.icon_mine_setting_default_head_img).into(viewDataBinding.ivUserHeadimg)
            viewDataBinding.tvUserName.text = it.nickname
            viewDataBinding.tvUserPhone.text = it.mobile
        })
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.rl_user_img -> showPicSelectTypeDialog()
            R.id.rl_user_name -> mContext.swapContentFragment(UpdateNickNameFragment())
            R.id.rl_address -> NavigationUtil.overlay(mContext, AddressListActivity::class.java)
            R.id.rl_user_phone -> mContext.swapContentFragment(UpdatePhoneStepFirstFragment())
            R.id.rl_update_pwd -> mContext.swapContentFragment(ForgetPwdFragment())
            R.id.rl_thrid_account -> mContext.swapContentFragment(ThirdAccountFragment())
            R.id.rl_login_out -> DialogUtil.getConfirmDialog(mContext, "提示", "确定要退出登录吗?", "确定", "取消", true, { dialog, which ->
                viewModel.loginOut {
                    EventBusUtil.sendEvent(GoToMainEvent())
                    mContext.finish()
                }
            }, { dialog, _ -> dialog.dismiss() }).show()
        }
    }

    private fun showPicSelectTypeDialog() {
        mBottomUpDialog.show()
        DialogUtil.setDialogWindowAttr(mBottomUpDialog, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM, R.style.DialogBottomAnimation)
    }

    private fun getFilePath(): Uri? {
        val fileDir = FileUtil.getOwnCacheDirectory(mContext, Utils.getApp().packageName + "/cache/temp/")
        FileUtils.createOrExistsDir(fileDir)
        val name = System.currentTimeMillis().toString()
        val file = FileUtils.getFileByPath(fileDir.absolutePath + "/" + name + ".jpg")
        return Uri.fromFile(file)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        takePhoto.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }
}